<template>
  <!-- 导航栏 -->
  <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)" />
  <!-- 搜索框 -->
  <div class="search">
    <van-search v-model="value" clearable />
    <van-button type="danger" @click="goSearch(value)">搜索</van-button>
  </div>
  <!-- 历史记录 -->
  <div class="history" v-if="history.length > 0">
    <div>
      <h3>最近搜索</h3>
      <van-icon name="delete-o" @click="clear" />
    </div>
    <div>
      <ul>
        <li v-for="item in history" :key="item" @click="goSearch(item)">
          {{ item }}
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { getHistoryList, setHistoryList } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data() {
    return {
      value: '',
      history: getHistoryList()
    }
  },
  methods: {
    goSearch(value) {
      if (value === '') {
        return
      }
      const index = this.history.indexOf(value)
      if (index !== -1) {
        this.history.splice(index, 1)
      }
      this.history.unshift(value)
      setHistoryList(this.history)
      this.$router.push(`/searchlist?search=${value}`)
    },
    clear() {
      this.history = []
      setHistoryList([])
    }
  }
}
</script>
<style scoped lang="less">
@keyframes blink {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
.search {
  display: flex;
}

.van-search {
  flex: 6;
  padding-right: 0px;
  :deep(.van-cell) {
    padding-right: 0px;
  }
  :deep(.van-field__control) {
    animation: blink 1s infinite;
  }
}

.van-button {
  height: 34px;
  margin-top: 12px;
  flex: 1;
  margin-right: 5px;
}

.history {
  position: relative;
  margin-top: 5px;
  h3 {
    font-weight: normal;
    font-size: 15px;
    margin-left: 12px;
    color: grey;
  }
  .van-icon {
    position: absolute;
    top: 2px;
    right: 5px;
  }
  ul {
    margin-top: 12px;
    display: flex;
    padding: 0 10px;
    gap: 5%;
    justify-content: feex-start;
    flex-wrap: wrap;
    li {
      width: 30%;
      text-align: center;
      padding: 7px;
      border: 1px solid transparent;
      border-radius: 50px;
      background: #fff;
      font-family: sans-serif;
      font-size: 13px;
      line-height: 13px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-bottom: 10px;
      background-color: #f2f2f2;
      letter-spacing: 2px;
    }
  }
}
</style>
